<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type {
  DorisDatabaseTree,
  DorisTableStructure,
  DorisTableStatistics,
  DorisDataPreview,
  DorisPartition
} from '@/service/api/dataplatform/doris-storage';
import {
  getTableStructure,
  getTableStatistics,
  previewTableData,
  getPartitionList,
  deletePartition
} from '@/service/api/dataplatform/doris-storage';

const visible = ref(false);
const loading = ref(false);
const activeTab = ref('structure');

const currentNode = ref<DorisDatabaseTree | null>(null);
const tableStructure = ref<DorisTableStructure[]>([]);
const tableStatistics = ref<DorisTableStatistics | null>(null);
const dataPreview = ref<DorisDataPreview | null>(null);
const partitionList = ref<DorisPartition[]>([]);

const previewPageNum = ref(1);
const previewPageSize = ref(10);

/** 打开抽屉 */
async function open(node: DorisDatabaseTree) {
  currentNode.value = node;
  visible.value = true;
  activeTab.value = 'structure';

  // 加载表结构
  await loadTableStructure();
  // 加载统计信息
  await loadTableStatistics();
}

/** 加载表结构 */
async function loadTableStructure() {
  if (!currentNode.value?.databaseName || !currentNode.value?.tableName) return;

  try {
    loading.value = true;
    const { data } = await getTableStructure(
      currentNode.value.databaseName,
      currentNode.value.tableName
    );
    tableStructure.value = data || [];
  } catch (error) {
    console.error('加载表结构失败:', error);
    ElMessage.error('加载表结构失败');
  } finally {
    loading.value = false;
  }
}

/** 加载统计信息 */
async function loadTableStatistics() {
  if (!currentNode.value?.databaseName || !currentNode.value?.tableName) return;

  try {
    const { data } = await getTableStatistics(
      currentNode.value.databaseName,
      currentNode.value.tableName
    );
    tableStatistics.value = data;
  } catch (error) {
    console.error('加载统计信息失败:', error);
    ElMessage.error('加载统计信息失败');
  }
}

/** 加载数据预览 */
async function loadDataPreview() {
  if (!currentNode.value?.databaseName || !currentNode.value?.tableName) return;

  try {
    loading.value = true;
    const { data } = await previewTableData(
      currentNode.value.databaseName,
      currentNode.value.tableName,
      previewPageNum.value,
      previewPageSize.value
    );
    dataPreview.value = data;
  } catch (error) {
    console.error('加载数据预览失败:', error);
    ElMessage.error('加载数据预览失败');
  } finally {
    loading.value = false;
  }
}

/** 加载分区列表 */
async function loadPartitionList() {
  if (!currentNode.value?.storageId) return;

  try {
    loading.value = true;
    const { data } = await getPartitionList(currentNode.value.storageId);
    partitionList.value = data || [];
  } catch (error) {
    console.error('加载分区列表失败:', error);
    ElMessage.error('加载分区列表失败');
  } finally {
    loading.value = false;
  }
}

/** 标签页切换 */
function handleTabChange(tabName: string | number) {
  const name = String(tabName);
  if (name === 'preview' && !dataPreview.value) {
    loadDataPreview();
  } else if (name === 'partition' && partitionList.value.length === 0) {
    loadPartitionList();
  }
}

/** 数据预览分页变化 */
function handlePreviewPageChange(page: number) {
  previewPageNum.value = page;
  loadDataPreview();
}

/** 数据预览每页大小变化 */
function handlePreviewSizeChange(size: number) {
  previewPageSize.value = size;
  previewPageNum.value = 1;
  loadDataPreview();
}

/** 删除分区 */
async function handleDeletePartition(partition: DorisPartition) {
  if (!currentNode.value?.databaseName || !currentNode.value?.tableName) return;

  try {
    await ElMessageBox.confirm(
      `确定要删除分区 "${partition.partitionName}" 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await deletePartition(
      currentNode.value.databaseName || '',
      currentNode.value.tableName || '',
      partition.partitionName || ''
    );

    ElMessage.success('删除分区成功');
    await loadPartitionList();
    await loadTableStatistics();
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除分区失败:', error);
      ElMessage.error('删除分区失败');
    }
  }
}

/** 格式化数据大小 */
function formatDataSize(bytes: number): string {
  if (!bytes) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let size = bytes;
  let unitIndex = 0;
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  return `${size.toFixed(2)} ${units[unitIndex]}`;
}

defineExpose({
  open
});
</script>

<template>
  <el-drawer v-model="visible" :title="`表详情: ${currentNode?.tableName || ''}`" size="70%" destroy-on-close>
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <!-- 表结构 -->
      <el-tab-pane label="表结构" name="structure">
        <el-table v-loading="loading" :data="tableStructure" border stripe style="width: 100%">
          <el-table-column prop="fieldName" label="字段名" width="180" />
          <el-table-column prop="fieldType" label="字段类型" width="120" />
          <el-table-column label="允许为空" width="100" align="center">
            <template #default="scope">
              <el-tag v-if="scope && scope.row" :type="scope.row.nullable ? 'success' : 'danger'" size="small">
                {{ scope.row.nullable ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="defaultValue" label="默认值" width="120" />
          <el-table-column label="主键" width="80" align="center">
            <template #default="scope">
              <el-tag v-if="scope && scope.row && scope.row.isPrimaryKey" type="warning" size="small">
                主键
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="comment" label="注释" show-overflow-tooltip />
        </el-table>
      </el-tab-pane>

      <!-- 统计信息 -->
      <el-tab-pane label="统计信息" name="statistics">
        <el-descriptions v-if="tableStatistics" :column="2" border>
          <el-descriptions-item label="数据库名称">
            {{ tableStatistics.databaseName }}
          </el-descriptions-item>
          <el-descriptions-item label="表名称">
            {{ tableStatistics.tableName }}
          </el-descriptions-item>
          <el-descriptions-item label="表类型">
            <el-tag>{{ tableStatistics.tableType }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="行数">
            {{ tableStatistics.rowCount?.toLocaleString() || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="数据大小">
            {{ tableStatistics.dataSizeFormatted }}
          </el-descriptions-item>
          <el-descriptions-item label="分区数量">
            {{ tableStatistics.partitionCount || 0 }}
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>

      <!-- 数据预览 -->
      <el-tab-pane label="数据预览" name="preview">
        <el-table v-loading="loading" :data="dataPreview?.rows || []" border stripe style="width: 100%"
          max-height="500">
          <el-table-column v-for="column in dataPreview?.columns || []" :key="column" :prop="column" :label="column"
            show-overflow-tooltip min-width="120" />
        </el-table>

        <el-pagination v-if="dataPreview" v-model:current-page="previewPageNum" v-model:page-size="previewPageSize"
          :total="dataPreview.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 16px; justify-content: flex-end" @current-change="handlePreviewPageChange"
          @size-change="handlePreviewSizeChange" />
      </el-tab-pane>

      <!-- 分区信息 -->
      <el-tab-pane label="分区信息" name="partition">
        <el-table v-loading="loading" :data="partitionList" border stripe style="width: 100%">
          <el-table-column prop="partitionName" label="分区名称" width="200" />
          <el-table-column prop="partitionType" label="分区类型" width="120" />
          <el-table-column prop="partitionValue" label="分区值" show-overflow-tooltip />
          <el-table-column label="行数" width="150">
            <template #default="scope">
              {{ scope && scope.row ? (scope.row.rowCount?.toLocaleString() || 0) : 0 }}
            </template>
          </el-table-column>
          <el-table-column label="数据大小" width="150">
            <template #default="scope">
              {{ scope && scope.row ? formatDataSize(scope.row.dataSize) : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button v-if="scope && scope.row" type="danger" link size="small"
                @click="handleDeletePartition(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-drawer>
</template>

<style scoped lang="scss">
:deep(.el-drawer__body) {
  padding: 20px;
}
</style>
